package com.ipzoe.web.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ipzoe.mem.domain.Member;
import com.ipzoe.mem.domain.MemberSobotRecord;
import com.ipzoe.mem.service.IMemberService;
import com.ipzoe.mem.service.IMemberSobotRecordService;
import com.ipzoe.web.module.open.SobotApiManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Component
public class SobotTask {

    private static final String KEY_SOBOT_RECORD_START_TIME = "sobot:record:starttime";

    private static final String DEFAULT_START_TIME = "2020-12-30 00:00:00";

    @Autowired
    private SobotApiManager sobotApiManager;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IMemberSobotRecordService memberSobotRecordService;
    @Autowired
    private IMemberService memberService;

    @Transactional(rollbackFor = Exception.class)
    public void saveRecord(){

        Object startTimeObj = redisTemplate.opsForValue().get(KEY_SOBOT_RECORD_START_TIME);

        String startTime = DEFAULT_START_TIME;
        if(startTimeObj != null){
            startTime = String.valueOf(startTimeObj);
            Date startTimeDate = DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss");
            startTime = DateUtil.offset(startTimeDate, DateField.SECOND, 1).toString("yyyy-MM-dd HH:mm:ss");
        }
        Date startTimeDate = DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss");

        Date today = new Date();
        JSONArray jsonArray = sobotApiManager.getRecords(startTime, DateUtil.format(today, "yyyy-MM-dd HH:mm:ss"), 0, 1, 100);
        if(CollUtil.isNotEmpty(jsonArray)){
            //倒叙第一个即为新的开始时间
            AtomicReference<String> newStartTimeStr = new AtomicReference<>("");

            List<MemberSobotRecord> memberRecordList = Lists.newArrayList();
            jsonArray.forEach(t->{
                JSONObject obj = (JSONObject) t;
                if(StrUtil.isNotEmpty(obj.getString("voice_aliyun_url"))){

                    String caller = obj.getString("caller");
                    LambdaQueryWrapper<Member> lqw = new QueryWrapper<Member>().lambda()
                            .eq(Member::getMobile1, caller);
                    Member member = memberService.getOne(lqw);
                    if(member != null){
                        String time = DateUtil.format(DateUtil.date(obj.getLong("start_time")), "yyyy-MM-dd HH:mm:ss");
                        if(StrUtil.isEmpty(newStartTimeStr.get())){
                            newStartTimeStr.set(time);
                        }
                        memberRecordList.add(MemberSobotRecord.builder()
                                .fileUrl(obj.getString("voice_aliyun_url"))
                                .memberId(member.getId())
                                .startTime(time)
                                .build());
                    }

                }
            });

            if(CollUtil.isNotEmpty(memberRecordList)){
                memberSobotRecordService.saveBatch(memberRecordList);
                if(StrUtil.isNotEmpty(newStartTimeStr.get())){
                    redisTemplate.opsForValue().set(KEY_SOBOT_RECORD_START_TIME, newStartTimeStr.get());
                }
            }
        }


    }
}
